有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java在httpSession中存储扩展对象

在下面的代码中,learning是一个学习实例,我想将其保存为http会话的原样

learning = new Learning(learningContext);
HttpSession webSession = request.getSession();
webSession.setAttribute("learning", learning);
Learning learnTest = webSession.getAttribute("learning");

当我运行下面的代码时,我得到:

Incompatible types
Learning learnTest = webSession.getAttribute("learning")      
required: Learning
found:    Object

我可以将非通用对象保存到会话中吗?有没有其他方法可以做到这一点


共 (2) 个答案

  1. # 1 楼答案

    javadoc for HttpSession.getAttribute说:

    java.lang.Object getAttribute(java.lang.String name) Returns the object bound with the specified name in this session, or null if no object is bound under the name.

    我的意思是,通过构造,它总是返回一个简单的对象。正如你所知道(或希望)的那样,你已经在那里放置了一个Learning,你只需要做一个显式转换:

    Learning learnTest = (Learning) webSession.getAttribute("learning");
    
  2. # 2 楼答案

    你需要像这样投射物体-

    Learning learnTest = (Learning) webSession.getAttribute("learning")
    

    您需要强制转换为特定类型,因为getAttribute的返回类型是Object